const {getRandom,jwtsign,expiresIn} = require("../utils")
const jwt = require("jsonwebtoken")
const connectiondb = require("../sql/mysql")
/* 
    TODO 获取验证码 --邹光山
*/
function code(req,res){
    //给前端一个随机的验证码
    res.send({code:200,msg:"获取验证码成功",data:getRandom(1000,9999)})
}


/* 
    TODO 登录操作 --邹光山
*/
async function login(req,res){
    /* 
        1. 获取登录的账号和密码
        2. 编写SQL语句
        3. 将SQL语句执行
        4. 将得到结果返回前端
    */
    const {ausername,apassword} = req.body;
    const sql = "select * from admin where name = ? and password = ?";
    const result = await connectiondb(sql,[ausername,apassword])
    if(result.length){
        const token = jwt.sign({userinfo:result[0]},jwtsign,{expiresIn})
        res.send({code:200,msg:"登录成功",data:result[0],token})
    }else{
        res.send({code:302,msg:"登录失败"})
    }
}

//获取头像操作 --邹光山
async function avrtor(req,res){
    const name=req.body;
    console.log(name);
    const name1=name.username;
    
    const sql="select avrtor from admin where name=?";
    const result=await connectiondb(sql,[name1])
    if(result.length){
        res.send({code:200,msg:"有头像",data:result[0]})

    }
    else{
        res.send({code:301,msg:"用户不存在"})
    }
}
//暴露
module.exports = {
    code,
    login,
    avrtor
}